package qmlt.learning.decisiontree.control;

import java.util.HashMap;
import java.util.Map;

import qmlt.dataset.DataSet;
import qmlt.dataset.Instance;
import qmlt.dataset.utils.DataSetUtils;
import qmlt.learning.decisiontree.DecisionTree;
import qmlt.learning.decisiontree.Node;
import qmlt.learning.decisiontree.utils.DecisionTreeUtils;

public class PessimisticPruner implements PruneController
{
    private DataSet               validateSet;

    private DecisionTree          tree;

    private Map<Instance, Object> predictions = new HashMap<Instance, Object>();

    public PessimisticPruner(DataSet validateSet)
    {
        this.validateSet = validateSet;
    }

    @Override
    public void prune(DecisionTree tree)
    {
        this.tree = tree;
        while (true)
        {
            predictValidateSet();
            if (!pruneHelper(this.tree.getRoot()));
            {
                break;
            }
        }
    }

    private void predictValidateSet()
    {
        predictions.clear();
        for (Instance inst : validateSet.getInstances())
        {
            Object p = tree.predict(inst);
            predictions.put(inst, p);
        }
    }

    private boolean pruneHelper(Node node)
    {
        if (tryPrune(node))
        {
            doPrune(node);
            return true;
        }
        else
        {
            boolean rst = false;
            for (Node child : node.children.values())
            {
                rst = rst || pruneHelper(child);
            }
            return rst;
        }
    }

    private boolean tryPrune(Node node)
    {
        int n = node.instances.size();
        double nT = DecisionTreeUtils.countMislabeled(node, predictions) + node.getSubtreeLeafCount() * 0.5;
        double nTpruned = DecisionTreeUtils.countMislabeledIfPruned(node, DataSetUtils
                .findMajorClass(node.instances)) + 0.5;
        double std = Math.sqrt((nT * (n - nT)) / n);
        if (nT < nTpruned - std)
            return false;
        return true;
    }

    private void doPrune(Node nodeToPrune)
    {
        nodeToPrune.children.clear();
        nodeToPrune.targetClass = DataSetUtils.findMajorClass(nodeToPrune.instances);
    }

    @Override
    public DataSet getValidateSet()
    {
        return validateSet;
    }
}
